//package com.yunxin.core.domain.service.order.impl;
//
//import cn.hutool.core.collection.CollUtil;
//import cn.hutool.core.collection.ListUtil;
//import cn.hutool.core.date.DatePattern;
//import cn.hutool.core.date.DateUtil;
//import cn.hutool.core.exceptions.ExceptionUtil;
//import cn.hutool.core.map.multi.ListValueMap;
//import cn.hutool.core.util.ObjUtil;
//import cn.hutool.core.util.StrUtil;
//import cn.hutool.crypto.SecureUtil;
//import com.baomidou.dynamic.datasource.annotation.DS;
//import com.yunxin.common.exception.BusinessException;
//import com.yunxin.common.utils.JacksonUtils;
//import com.yunxin.core.application.dto.order.BalanceProduct;
//import com.yunxin.core.application.dto.product.ProductInfoDTO;
//import com.yunxin.core.application.seceiver.message.ProductStatistics;
//import com.yunxin.core.application.service.ProductQueryGatewayService;
//import com.yunxin.core.domain.external.channel.ChannelProhibitProductService;
//import com.yunxin.core.domain.external.merchant.MerchantExternalService;
//import com.yunxin.core.domain.external.product.ProductAllocationDetail;
//import com.yunxin.core.domain.external.product.ProductExternalService;
//import com.yunxin.core.domain.external.product.ProductPriceInfo;
//import com.yunxin.core.domain.model.order.*;
//import com.yunxin.core.domain.model.product.ProductThrowInConfig;
//import com.yunxin.core.domain.model.product.ProductThrowInConfigRepository;
//import com.yunxin.core.domain.service.order.LibraryOrPushOrderOrderStatisticsService;
//import com.yunxin.core.domain.service.order.OrderService;
//import com.yunxin.core.domain.service.order.OrderUserApplyQWService;
//import com.yunxin.core.domain.service.product.ProductQualityConfigService;
//import com.yunxin.core.infra.common.order.OrderScheduling;
//import com.yunxin.core.infra.common.order.enums.OrderAllocationStatusEnum;
//import com.yunxin.core.infra.common.order.enums.OrderAllocationTypeEnum;
//import com.yunxin.core.infra.common.order.enums.OrderLockKey;
//import com.yunxin.core.infra.common.order.utils.AllocationAttributeDetermineUtils;
//import com.yunxin.core.infra.common.product.enums.ProductAbutmentTypeEnum;
//import com.yunxin.core.infra.persistence.converter.OrderConverter;
//import com.yunxin.core.infra.persistence.entity.product.ProductQualityConfig;
//import com.yunxin.core.infra.persistence.mapper.product.ProductThrowInConfigExtendMapper;
//import com.yunxin.core.utils.infra.common.constant.CoreResultCode;
//import com.yunxin.core.utils.infra.support.lock.DistributedLock;
//import com.yunxin.core.utils.infra.support.lock.DistributedLockFactory;
//import com.yunxin.core.utils.infra.support.request.LibraryOrderDTO;
//import com.yunxin.core.utils.infra.support.request.PushOrderDTO;
//import com.yunxin.core.utils.infra.support.request.merchant.BaseActionListener;
//import com.yunxin.core.utils.infra.support.request.merchant.MerchantActionCodeEnum;
//import com.yunxin.core.utils.infra.support.request.merchant.MerchantActionFactory;
//import com.yunxin.core.utils.infra.utils.DateFormatUtils;
//import com.yunxin.core.utils.infra.utils.IdCardNumberUtils;
//import com.yunxin.point.domain.external.PointExternalService;
//import com.yunxin.point.domain.external.SaveUserBuryingPointData;
//import com.yunxin.point.infra.common.UserBuryingPointTypeEnum;
//import com.yunxin.statistics.infra.common.ProductStatisticsTypeEnum;
//import com.yunxin.statistics.infra.common.PromotionStatisticsTypeEnum;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
//import org.springframework.stereotype.Component;
//
//import java.math.BigDecimal;
//import java.util.*;
//import java.util.concurrent.CountDownLatch;
//import java.util.function.Function;
//import java.util.stream.Collectors;
//
///**
// * @author zero°
// * @since 2023-08-22
// */
//@DS("core")
//@Slf4j
//@Component
//@RequiredArgsConstructor
//public class OrderUserAllocationMatchHandle {
//
//    private static final String LOCK_KEY = "lock";
//
//
//    @Value("${allocation.limit.day}")
//    private int allocationLimitDay;
//
//    @Value("${allocation.default.productId}")
//    private Long allocationDefaultProductId;
//
//
//    @Value("${allocation.default.merchantId}")
//    private Long allocationDefaultMerchantId;
//
//    private final OrderUserApplyAllocationRepository orderUserApplyAllocationRepository;
//
//    private final OrderUserApplyAllocationStockHandle orderUserApplyAllocationStockHandle;
//
//    private final OrderService orderService;
//
//    private final ProductExternalService productExternalService;
//
//    private final MerchantExternalService merchantExternalService;
//
//    private final ChannelProhibitProductService channelProhibitProductService;
//
//    private final PointExternalService pointExternalService;
//
//    private final DistributedLockFactory distributedLockFactory;
//
//    private final OrderStatisticsHandle orderStatisticsHandle;
//
//    private final MerchantActionFactory merchantActionFactory;
//
//    private final ProductQualityConfigService productQualityConfigService;
//
//    private final LibraryOrPushOrderOrderStatisticsService libraryOrderStatisticsService;
//
//    @Qualifier("asyncDownloadFileThreadPool")
//    private final ThreadPoolTaskExecutor threadPoolTaskExecutor;
//
//    private final ProductThrowInConfigExtendMapper productThrowInConfigExtendMapper;
//
//    private static final Integer[] AbutmentType = {4,5};
//
//    private final ProductQueryGatewayService productQueryGatewayService;
//
//    private final ProductThrowInConfigRepository productThrowInConfigRepository;
//
//
//    private final OrderScheduling orderScheduling;
//
//    private final OrderUserApplyQWService orderUserApplyQWService;
//
//    //不进行进件请求的产品id,需要在页面发起进件
//    private static List<Long> noPushProductIds = new ArrayList<>();
//    private static List<Long> productIds = new ArrayList<>();
//
//    static {
//        noPushProductIds.add(20L);//橙易通
//        noPushProductIds.add(28L);//好汇推2.0
//        noPushProductIds.add(31L);//好汇推4.0
//        noPushProductIds.add(58L);//微银信用
//        noPushProductIds.add(65L);//信用帮
//        noPushProductIds.add(72L);//如小愿30
//        noPushProductIds.add(66L);//企惠通
//        noPushProductIds.add(73L);//互融智贷
//        noPushProductIds.add(115L);//天下分期
//        noPushProductIds.add(124L);//浩瀚有借
////===========前端通知进件的产品================
//        productIds.add(20L);//橙易通
//        productIds.add(58L);//微银信用
//        productIds.add(66L);//企惠通
//        productIds.add(73L);//互融智贷
//        productIds.add(65L);//信用帮
//        productIds.add(72L);//如小愿30
//        productIds.add(115L);//天下分期
//       // productIds.add(124L);//浩瀚有借
//        noPushProductIds.add(127L);//小美易融
//        noPushProductIds.add(121L);//云起信用
//        noPushProductIds.add(130L);//小美易融2
//
//    }
//
//    /**
//     * 订单分配
//     * 第一步：获取所有上架且按表单结算的产品，根据id升序
//     * 第二步：遍历list，得到条件符合的产品集合list
//     * 第三步：将符合条件的产品list根据价格分组（map，key为价格，value为对应的产品集合list），并按价格（key）降序排序
//     * 第四步：获取第一个key的value值（即最高价格的产品数据），如果value值对应的list只有一条数据，则返回该产品，如果不是一条数据，则再根据权重分组，并按权重降序排序，得到新的map集合（key为权重，value为对应的产品集合list）
//     * 第五步：获取第一个key的value值（即最高权重的产品数据），如果value值对应的list只有一条数据，则返回该产品，如果不是一条数据，则获取上一次该价格该权重的产品id（redis缓存），再遍历list，循环判断当前循环产品id是否大于分配单最新id，如果是，则返回该产品，如果不是，则继续下一条。判断最后获取的产品是否为空，如果为空则取list第一条数据
//     * 第六步：保存分配单，更新该价格该权重redis的产品id
//     *
//     * @param userApply   userApply
//     * @param applyDetail applyDetail
//     * @param clientIp    clientIp
//     * @return AllocationMerchantDTO
//     */
//    public AllocationOrderUserApplyResult orderAllocation(OrderUserApply userApply, OrderUserApplyDetail applyDetail, String clientIp) {
//        AllocationMerchant dto = new AllocationMerchant();
//        Long channelId = userApply.getChannelId();
//        // 获取所有上架的产品
//        List<ProductAllocationDetail> products = productExternalService.listProductAllocationDetailResult(userApply.getChannelPromotionCode(), channelId);
//
//        //设置用户明细属性
//        checkInitUserDetail(userApply, applyDetail);
//
//        log.info("订单no={},渠道code={}尝试获取锁！", userApply.getApplyOrderNo(), userApply.getChannelPromotionCode());
//        String userCode = userApply.getUserCode();
//        if (orderScheduling.tryAcquire()) {
//            // 分布式锁 用户code为key
//            DistributedLock lock = distributedLockFactory.provideDistributedLock(OrderLockKey.ORDER_USER_APPLY_ALLOCATION.getPrefix() + userCode);
//            if (lock.tryLock(OrderLockKey.ORDER_USER_APPLY_ALLOCATION.getWaitTime(), OrderLockKey.ORDER_USER_APPLY_ALLOCATION.getReleaseTime(), OrderLockKey.ORDER_USER_APPLY_ALLOCATION.getTimeUnit())) {
//                try {
//
//                    // 所有撞库成功的产品集合
////                    List<ProductAllocationDetail> successProducts = new CopyOnWriteArrayList<>();
//                    List<ProductAllocationDetail> successProducts = Collections.synchronizedList(new ArrayList<>());
//                    // 获取所有撞库成功的产品
//                    matchProduct(clientIp, userApply, applyDetail, products, successProducts);
//
//                    // 获取撞库成功的产品中单价最高的那个产品详情
//                    ProductAllocationDetail detailDTO = getProductAllocationDetail(successProducts,userApply.getChannelPromotionCode());
//
//                    // 如果是企业微信过来的 则直接返回 不分配
//                    List<Long> productIds = productThrowInConfigExtendMapper.selectThrowInConfigByAbutmentType(AbutmentType);
//
//                    AllocationOrderUserApplyResult resultDTO = new AllocationOrderUserApplyResult();
//                    resultDTO.setIsAbutmentType(2);
//
//                    if (Objects.nonNull(detailDTO)) {
//                        log.info("{}获取撞库成功的产品中单价最高的那个产品详情{},(-1代表无)", userApply.getApplyOrderNo(), ObjUtil.defaultIfNull(detailDTO.getProductId(), -1));
//                        //腰带钱包是1 进腰带就是兜底
//                        resultDTO.setIsBottom(detailDTO.getProductId() == 1 ? 1 : 2);
//
//                        String apiLibraryOrderNo = detailDTO.getApiLibraryOrderNo();
//                        Integer abutmentType = detailDTO.getAbutmentType();
//                        Integer apiEnumVal = ProductAbutmentTypeEnum.API.getValue();
//                        Long productId = detailDTO.getProductId();
//                        //检查  产品为api对接且api撞库订单号不为空,未在不推送名单,  则推送api商户
//                        DistributedLock productLock = distributedLockFactory.provideDistributedLock(OrderLockKey.ORDER_PUSH_ORDER.getPrefix() + productId);
//
//                        //不是企微
//                        if (!productIds.contains(detailDTO.getProductId()) && productLock.tryLock(OrderLockKey.ORDER_PUSH_ORDER.getWaitTime(), OrderLockKey.ORDER_PUSH_ORDER.getReleaseTime(), OrderLockKey.ORDER_PUSH_ORDER.getTimeUnit())) {
//                            try {
//                                boolean b = orderUserApplyAllocationStockHandle.checkProductStock(detailDTO.getProductId(), detailDTO.getTotalLimit());
//                                if (b) {
//                                    orderUserApplyAllocationStockHandle.determineProductStock(detailDTO.getProductId());
//                                    //api 发起进件请求
//                                    if (apiEnumVal.equals(abutmentType) && !CollUtil.safeContains(noPushProductIds, productId) && StrUtil.isNotBlank(apiLibraryOrderNo)) {
//                                        //同一产品并发存在库存超卖问题
//                                        try {
//                                            detailDTO = pushMerchantOrderByApi(clientIp, userApply, applyDetail, detailDTO);
//                                        } catch (Exception e) {
//                                            log.error("订单no={},渠道code={},product={},接口进件失败,e={}", userApply.getApplyOrderNo(), userApply.getChannelPromotionCode(), productId, ExceptionUtil.stacktraceToOneLineString(e, 1000));
//                                            detailDTO = null;
//                                            orderUserApplyAllocationStockHandle.releaseProductStock(dto.getProductId());
//                                        }
//                                    }
//                                }else {
//                                    log.warn("产品库存不足,productId={}", productId);
//                                    detailDTO = null;
//                                }
//                            } finally {
//                                productLock.unlock();
//                            }
//                        }else {
//                            if (!productIds.contains(detailDTO.getProductId())) {
//                                log.error("订单no={},渠道code={},product={},并发进件获取锁失败", userApply.getApplyOrderNo(), userApply.getChannelPromotionCode(), productId);
//                                detailDTO = null;
//                            }
//                        }
//                    }
//
//
//                    String redisCashField = null;
//
//                    //api进件可能失败需要判断 产品全关也需要判断
//                    if (Objects.nonNull(detailDTO)) {
//                        dto.setMerchantId(detailDTO.getMerchantId());
//                        dto.setProductId(detailDTO.getProductId());
//                        dto.setChargedPrice(detailDTO.getChargedPrice());
//                        dto.setWeight(detailDTO.getWeight());
//                        dto.setApiOrderUrl(detailDTO.getApiOrderUrl());
//                        dto.setApiLibraryOrderNo(detailDTO.getApiLibraryOrderNo());
//                        redisCashField = dto.getChargedPrice() + "" + dto.getWeight();
//                    }
//                    try {
//
//
//                        //兜底判断
//                        boolean bottomCheck = roundBottomCheck(dto, userApply);
//                        if (bottomCheck) {
//                            log.info("未分配到产品，兜底处理,applyOrderNo={}", applyDetail.getApplyOrderNo());
//                            dto.setMerchantId(allocationDefaultMerchantId);
//                            dto.setProductId(allocationDefaultProductId);
//                            resultDTO.setIsBottom(1);
//                        }
//
//                        // 分配商户id
//                        long accountId = allocationMerchantAccountId(dto.getMerchantId());
//                        dto.setAccountId(accountId);
//                        userApply.setAllocationStatus(OrderAllocationStatusEnum.ALLOCATION.getValue());
//                        userApply.setAllocationTime(new Date());
//                        userApply.setVersion(userApply.getVersion() + 1);
//                        OrderUserApplyAllocation orderUserApplyAllocation = bulidOrderUserApplyAllocation(userApply, applyDetail, dto);
//                        //该产品是企微进入此方法
//                        if (productIds.contains(dto.getProductId())) {
//                            //获取场景链接
//                            String url = orderUserApplyQWService.getWxWorkUrl(userApply,dto.getProductId(),clientIp);
//                            ProductInfoDTO result = productQueryGatewayService.getProductInfo(dto.getProductId());
//                            ProductThrowInConfig throwInConfig = productThrowInConfigRepository.getProductThrowInConfigByProductId(dto.getProductId());
//                            List<OrderUserApply> orderUserApply = orderService.selectOrderUserApplyAllocationByUserCode1(userApply.getUserCode(), orderUserApplyAllocation.getProductId());
//                            if (CollUtil.isNotEmpty(orderUserApply)) {
//                                resultDTO.setIsBottom(1);
//                            }
//                            log.info("企业微信过来的 则直接返回");
//                            resultDTO.setUserApply(userApply);
//                            resultDTO.setOrderUserApplyAllocation(orderUserApplyAllocation);
//                            resultDTO.setRedisCashField(redisCashField);
//                            resultDTO.setIsAbutmentType(1);
//                            resultDTO.setClientIp(clientIp);
//                            resultDTO.setZhzxUrl(result.getJumpUrl());
//                            // TODO 如果获取到的场景链接不为空则重写url
//                            if (Objects.nonNull(url)) resultDTO.setZhzxUrl(url);
//                            resultDTO.setSex(applyDetail.getSex());
//                            resultDTO.setTotalLimit(detailDTO.getTotalLimit());
//                            resultDTO.setProductId(throwInConfig.getBeProductId());
//                            resultDTO.setUserPhone(userApply.getUserPhone());
//                            return resultDTO;
//                        }
//                        // 保存分配单
//                        orderService.saveOrderUserApplyAllocation(userApply, orderUserApplyAllocation, redisCashField);
//                        // 订单分配成功处理
//                        allocationOrderSuccess(orderUserApplyAllocation, userApply, applyDetail.getSex(), clientIp);
//                        resultDTO.setAllocationOrderId(orderUserApplyAllocation.getId());
//                        resultDTO.setProductId(orderUserApplyAllocation.getProductId());
//                        log.info("订单分配成功处理：{}", orderUserApplyAllocation.getProductId());
//                        resultDTO.setApiUrl(dto.getApiOrderUrl());
//                        if (Objects.nonNull(detailDTO)) {
//                            if (detailDTO.getProtocol() != null) {
//                                resultDTO.setProtocol(detailDTO.getProtocol());
//                            }
//                            if(detailDTO.getPlanAuthProtocol()!=null){
//                                resultDTO.setPlanAuthProtocol(detailDTO.getPlanAuthProtocol());
//                            }
//                            if (detailDTO.getProductId() == 28 || detailDTO.getProductId() == 31
//                                ||detailDTO.getProductId()==127
//                                ||detailDTO.getProductId()==124L||detailDTO.getProductId()==130L
//                                ||detailDTO.getProductId()==115L) {
//                                resultDTO.setApiUrl(detailDTO.getApiLibraryOrderNo());
//                            }
//                        }
//                        log.info("该订单将要分发的产品id为：{}", resultDTO.getProductId());
//                        resultDTO.setOrderUserApplyAllocation(orderUserApplyAllocation);
//                        return resultDTO;
//                    } catch (Exception e) {
//                        log.error("订单分配异常,applyOrderNo={}, e", applyDetail.getApplyOrderNo(), e);
//                        orderUserApplyAllocationStockHandle.releaseProductStock(dto.getProductId());
//                        throw new BusinessException(CoreResultCode.ORDER_ALLOCATION_ORDER_ACCOUNT_ERROR);
//                    }
//                } finally {
//                    log.info("释放锁成功！{}", userApply.getChannelPromotionCode());
//                    lock.unlock();
//                    orderScheduling.release();
//                }
//            } else {
//                orderScheduling.release();
//                log.info("订单no={},渠道code={},重复提交", userApply.getApplyOrderNo(), userApply.getChannelPromotionCode());
//                throw new BusinessException("请勿频繁操作,稍后再试");
//            }
//        } else {
//            log.info("订单no={},渠道code={},获取锁失败", userApply.getApplyOrderNo(), userApply.getChannelPromotionCode());
//            throw new BusinessException(CoreResultCode.ORDER_ALLOCATION_ORDER_LOCK_ERROR);
//        }
//    }
//
//
//
//    //兜底流程判断
//    private boolean roundBottomCheck(AllocationMerchant dto, OrderUserApply userApply) {
//        //未匹配商户
//        if (Objects.isNull(dto.getMerchantId())) {
//            return true;
//        }
//        //未匹配产品
//        if (Objects.isNull(dto.getProductId())) {
//            return true;
//        }
//        if (dto.getProductId() == 1) {
//            return true;
//        }
////        //进入了分期贷
////        OrderUserApply fqdorderUserApply = orderService.selectOrderUserApplyAllocationByUserCode(userApply.getUserCode(), 36L);
////        if (Objects.nonNull(fqdorderUserApply)) {
////            return true;
////        }
//        //分配过这个产品
//        List<OrderUserApply> orderUserApply = orderService.selectOrderUserApplyAllocationByUserCode1(userApply.getUserCode(), userApply.getProductId());
//
//        if (CollUtil.isNotEmpty(orderUserApply)) {
//            return true;
//        }
//        return false;
//    }
//
//    /**
//     * 设置用户明细属性
//     *
//     * @param userApply
//     * @param applyDetail
//     */
//    private void checkInitUserDetail(OrderUserApply userApply, OrderUserApplyDetail applyDetail) {
//
//        Integer age = applyDetail.getAge();
//        if (Objects.isNull(age) && StringUtils.isNotBlank(userApply.getUserIdentityNo())) {
//            age = IdCardNumberUtils.X.getAgeForIdCard(userApply.getUserIdentityNo());
//            applyDetail.setAge(age);
//        }
//        Integer sex = applyDetail.getSex();
//        if (Objects.isNull(sex) && StringUtils.isNotBlank(userApply.getUserIdentityNo())) {
//            sex = IdCardNumberUtils.X.getSexIntFromIdCard(userApply.getUserIdentityNo());
//            applyDetail.setAge(sex);
//        }
//
//    }
//
//    /**
//     * 匹配产品
//     *
//     * @param clientIp        clientIp
//     * @param userApply       userApply
//     * @param applyDetail     applyDetail
//     * @param products        products
//     * @param successProducts successProducts
//     */
//    private void matchProduct(String clientIp, OrderUserApply userApply, OrderUserApplyDetail applyDetail, List<ProductAllocationDetail> products, List<ProductAllocationDetail> successProducts) {
//        if (CollUtil.isEmpty(products)) {
//            return;
//        }
//        // 匹配失败商户id
//        Set<Long> failMerchantIds = Collections.synchronizedSet(new HashSet<>());
//        // api撞库成功商户id
//        Set<Long> apiSuccessMerchantIds = Collections.synchronizedSet(new HashSet<>());
//
//        List<ProductQualityConfig> productQualityList = productQualityConfigService.lambdaQuery().in(ProductQualityConfig::getProductId, products.stream().map(ProductAllocationDetail::getProductId).toList()).list();
//        Map<Long, ProductQualityConfig> qualityConfigMap = productQualityList.stream().collect(Collectors.toMap(ProductQualityConfig::getProductId, Function.identity()));
//
//
//        //每次并发4个线程请求
//        List<List<ProductAllocationDetail>> productTaskList = ListUtil.partition(products, 4);
//
//        for (List<ProductAllocationDetail> productTasks : productTaskList) {
//
//
//            CountDownLatch latch = new CountDownLatch(productTasks.size());
//            // 按条件匹配产品
//            for (ProductAllocationDetail detailDTO : productTasks) {
//                threadPoolTaskExecutor.execute(() -> {
//                    try {
//                        long starTime = System.currentTimeMillis();
//                        boolean result = matchSimpleProduct(failMerchantIds, apiSuccessMerchantIds, detailDTO, clientIp, userApply, applyDetail, qualityConfigMap.get(detailDTO.getProductId()));
//                        long endTime = System.currentTimeMillis();
//                        log.info("产品{}撞库耗时={}", detailDTO.getProductId(), endTime - starTime);
//                        LibraryOrPushOrderStatistics statistics = new LibraryOrPushOrderStatistics();
//                        statistics.setApplyNo(applyDetail.getApplyOrderNo());
//                        statistics.setProductId(detailDTO.getProductId().intValue());
//                        statistics.setMerchantId(detailDTO.getMerchantId().intValue());
//                        statistics.setCrateTime(new Date());
//                        statistics.setStatus(2);
//                        statistics.setType(1);
//                        if (result) {
//                            statistics.setStatus(1);
//                            successProducts.add(detailDTO);
//                        }
//                        try {
//                            libraryOrderStatisticsService.saveLibraryOrderStatistics(statistics);
//                        } catch (Exception e) {
//                            log.error("撞库记录异常,applyOrderNo={},productId={}, e", applyDetail.getApplyOrderNo(), detailDTO.getProductId(), e);
//                        }
//                    } catch (Exception e) {
//                        log.error("多线程撞库异常,产品ProductAllocationDetail={},异常信息：{}", detailDTO, ExceptionUtil.stacktraceToString(e));
//                    } finally {
//                        latch.countDown();
//                    }
//                });
//            }
//            try {
//                latch.await();
//            } catch (InterruptedException e) {
//                log.error("CountDownLatch 等待被中断");
//            }
//        }
//
//        List<Long> longs = successProducts.stream().map(ProductAllocationDetail::getProductId).toList();
//        log.info("{}获取所有产品：{}", userApply.getApplyOrderNo(), longs);
//    }
//
//    /**
//     * 匹配单个产品
//     *
//     * @param failMerchantIds       failMerchantIds
//     * @param apiSuccessMerchantIds apiSuccessMerchantIds
//     * @param detailDTO             detailDTO
//     * @param clientIp              clientIp
//     * @param userApply             userApply
//     * @param applyDetail           applyDetail
//     * @return result
//     */
//    private boolean matchSimpleProduct(Set<Long> failMerchantIds, Set<Long> apiSuccessMerchantIds, ProductAllocationDetail detailDTO, String clientIp, OrderUserApply userApply, OrderUserApplyDetail applyDetail, ProductQualityConfig quality) {
//        // 如果商户id在失败的商户id集合内，则返回匹配失败
//        if (failMerchantIds.contains(detailDTO.getMerchantId())) {
//            return false;
//        }
//        // 如果是自营的产品，且商户下面的所有客服全部关闭 则直接返回
//        List<Long> accountIds = merchantExternalService.listAccountIdByMerchantId(detailDTO.getMerchantId());
//        if(detailDTO.getAbutmentType()==1 && CollUtil.isEmpty(accountIds)){
//            log.info("该商户下面的所有客服全部关闭,商户id={}", detailDTO.getMerchantId());
//            return false;
//
//        }
//
//        // 匹配结果
//        boolean matchResult = AllocationAttributeDetermineUtils.X.isMatchResult(detailDTO, applyDetail, applyDetail.getAge(), applyDetail.getSex());
//        boolean result = matchResult;
//        // 匹配成功
//        if (matchResult) {
//            Date endTime = new Date();
//            Date startTime = DateFormatUtils.X.getDayLater(endTime, allocationLimitDay);
//            // 查询商户规定时间内是否存在该用户订单，存在则跳过该商户所有产品z
//            Long allocationId = orderUserApplyAllocationRepository.getAllocationIdByUserAndMerchant(userApply.getUserCode(), detailDTO.getMerchantId(), startTime, endTime);
//            // 再判断该商户库存，产品数量是否已经超限，如果未超限则为true，否则false  todo
//
//            if (Objects.nonNull(allocationId)) {
//                failMerchantIds.add(detailDTO.getMerchantId());
//                log.warn("订单匹配商户异常,该用户已分配过该商户, userCode={},merchantId={}", userApply.getUserCode(), detailDTO.getMerchantId());
//                result = false;
//            } else {
//                // 判断产品库存,该产品当日是否已超限，如果未超限则为true，否则false
//                result = orderUserApplyAllocationStockHandle.checkProductStock(detailDTO.getProductId(), detailDTO.getTotalLimit());
//                if (result) {
//                    // 如果产品是API产品
//                    if (ProductAbutmentTypeEnum.API.getValue().equals(detailDTO.getAbutmentType())) {
//                        // 如果是api对接但是无对接策略，返回false
//                        BaseActionListener merchantActionListener = merchantActionFactory.getMerchantActionListener(detailDTO.getMerchantId());
//                        if (Objects.isNull(merchantActionListener)) {
//                            result = false;
//                        } else {
//                            // 判断商户是否api撞库成功
//                            if (apiSuccessMerchantIds.contains(detailDTO.getMerchantId())) {
//                                result = false;
//                            } else {
//                                LibraryOrderDTO libraryOrderDTO = new LibraryOrderDTO();
//                                libraryOrderDTO.setPhoneMd5(SecureUtil.md5(userApply.getUserPhone()));
//                                libraryOrderDTO.setClientIp(clientIp);
//                                libraryOrderDTO.setAge(applyDetail.getAge());
//                                libraryOrderDTO.setSex(applyDetail.getSex());
//                                libraryOrderDTO.setPhone(userApply.getUserPhone());
//                                libraryOrderDTO.setId(userApply.getId());
//                                libraryOrderDTO.setMerchantId(detailDTO.getMerchantId());
//                                libraryOrderDTO.setProductId(detailDTO.getProductId());
//                                libraryOrderDTO.setApplyOrderNo(applyDetail.getApplyOrderNo());
//                                libraryOrderDTO.setUserCode(userApply.getUserCode());
//                                if (quality.getAgeSwitch() == 1) {
//                                    libraryOrderDTO.setAge(quality.getAge());
//                                }
//                                if (quality.getSexSwitch() == 1) {
//                                    libraryOrderDTO.setSex(quality.getSex());
//                                }
//                                OrderConverter.converterBaseOrderDTO(libraryOrderDTO, userApply, applyDetail, quality);
//                                // 匹配撞库
//                                String apiResult = null;
//                                try {
//                                    apiResult = merchantActionListener.requestAction(MerchantActionCodeEnum.LIBRARY_ORDER, libraryOrderDTO);
//                                } catch (Exception e) {
//                                    log.error("执行分发错误", e);
//                                    result = false;
//                                }
//                                if (StringUtils.isBlank(apiResult)) {
//                                    result = false;
//                                } else {
//                                    if (productIds.contains(detailDTO.getProductId())) {
//                                        detailDTO.setApiOrderUrl(apiResult);
//                                        detailDTO.setApiLibraryOrderNo("三方通知进件");
//                                        if (apiResult.contains("YXY30_KEY")) {
//                                            String[] yxy30Keys = apiResult.split("YXY30_KEY");
//                                            detailDTO.setApiOrderUrl(yxy30Keys[0] + "=YXY30_KEY");
//                                            String[] protocolKeys = yxy30Keys[1].split("PlanAuthProtocolKey");
//                                            detailDTO.setProtocol(protocolKeys[0]);
//                                            detailDTO.setPlanAuthProtocol(protocolKeys[1]);
//                                        }
//                                    } else {
//                                        detailDTO.setApiLibraryOrderNo(apiResult);
//                                    }
//                                    apiSuccessMerchantIds.add(detailDTO.getMerchantId());
//                                }
//                            }
//
//                        }
//                    }
//                }
//            }
//        }
//        return result;
//    }
//
//    /**
//     * 获取产品分配详情
//     *
//     * @param successProducts      successProducts
//     * @param channelPromotionCode
//     * @return ProductAllocationDetail
//     */
//    private ProductAllocationDetail getProductAllocationDetail(List<ProductAllocationDetail> successProducts, String channelPromotionCode) {
//        if (CollUtil.isEmpty(successProducts)) {
//            return null;
//        }
//        log.error("channelPromotionCode={},撞库成功的产品={}", channelPromotionCode,successProducts.stream().map(ProductAllocationDetail::getProductId).toList());
//
//        successProducts = successProducts.stream().filter(it -> it.getProductId() != allocationDefaultProductId).toList();
//
//        if (CollUtil.isEmpty(successProducts)) {
//            return null;
//        }
//
//        if (successProducts.size() == 1) {
//           return orderUserApplyAllocationStockHandle.balanceStack3(successProducts, channelPromotionCode);
//        }
//        // 根据价格分组并按价格降序排序
//        Map<BigDecimal, List<ProductAllocationDetail>> groupByPriceMap = successProducts.stream().collect(Collectors.groupingBy(ProductAllocationDetail::getChargedPrice, () -> new TreeMap<>((Comparator.reverseOrder())), Collectors.toList()));
//        // 获取第一个key的产品集合(即价格最高的产品)
//        List<ProductAllocationDetail> priceProducts = groupByPriceMap.values().stream().findFirst().get();
//        //只有一个数据则取当条数据
//        if (priceProducts.size() == 1) {
//           return orderUserApplyAllocationStockHandle.balanceStack3(priceProducts, channelPromotionCode);
//        }
//        // 根据权重分组并按权重降序排序(用最高价产品集合)
//        Map<Integer, List<ProductAllocationDetail>> groupByWeightMap = priceProducts.stream().collect(Collectors.groupingBy(ProductAllocationDetail::getWeight, () -> new TreeMap<>((Comparator.reverseOrder())), Collectors.toList()));
//        // 获取第一个key的产品集合(即权重最高的产品)
//        List<ProductAllocationDetail> weightProducts = groupByWeightMap.values().stream().findFirst().get();
//        // 获取最新分配单的产品id
//        return orderUserApplyAllocationStockHandle.balanceStack3(weightProducts, channelPromotionCode);
//    }
//
//    /**
//     * 分配商户账户
//     *
//     * @param merchantId merchantId
//     * @return accountId
//     */
//    public Long allocationMerchantAccountId(Long merchantId) {
//
//        /**
//         * 分配逻辑更改为
//         * 1.查询该商户下所有的团队
//         * 2.判断当前订单的产品是否与商户下的团队有关联，有关联得团队根据权重排序，取出权重最大的那个
//         * 3.获取团队已分配数量和阈值数，已分配数量小于阈值则继续分配，反之则取出下一个团队，以此循环，直到没有团队
//         * 4.获取团队下所有的人员（根据权重倒序，排序越前）
//         */
//        // 2. 子账户平均分配(即获取分配单最后一条记录, 如果开启接单的子账号大于最后一条记录账户id-取第一条,则分配给该子账户)
//        // 3. 如果账号重复启用，可能会存在没有分配到订单的情况 场景: 本次账号id为1,3,7且商户当前最后一条分配单账号id为3,则本次分配账号id为7,
//        // 如果下一次账号id为1,3,5,7那么下一次商户当前最后一条分配单账号id为7,则本次分配账号id为1,跳过了5
//        List<Long> accountIds = merchantExternalService.listAccountIdByMerchantId(merchantId);
//        if (accountIds.isEmpty()) {
//            return 0L;
//        }
//        Long accountId = orderUserApplyAllocationRepository.getAllocationOrderLastAccountIdByMerchant(merchantId);
//        if (Objects.isNull(accountId)) {
//            return accountIds.get(0);
//        }
//        int index = 0;
//        for (Long id : accountIds) {
//            if (id > accountId) {
//                accountId = id;
//                index = 1;
//                break;
//            }
//        }
//        // index = 0说明查询到的id为当前接单中的子账户中最大的,重新取第一条(即下一循环)
//        if (index == 0) {
//            return accountIds.get(0);
//        }
//        return accountId;
//    }
//
//    /**
//     * 构建订单分配单
//     *
//     * @param userApply          userApply
//     * @param applyDetail        applyDetail
//     * @param allocationMerchant allocationMerchant
//     * @return OrderUserApplyAllocation
//     */
//    private OrderUserApplyAllocation bulidOrderUserApplyAllocation(OrderUserApply userApply, OrderUserApplyDetail applyDetail, AllocationMerchant allocationMerchant) {
//        OrderUserApplyAllocation orderUserApplyAllocation = new OrderUserApplyAllocation();
//        orderUserApplyAllocation.setUserCode(userApply.getUserCode());
//        orderUserApplyAllocation.setUserName(userApply.getUserName());
//        orderUserApplyAllocation.setUserPhone(userApply.getUserPhone());
//        orderUserApplyAllocation.setUserIdentityNo(userApply.getUserIdentityNo());
//        orderUserApplyAllocation.setApplyOrderNo(userApply.getApplyOrderNo());
//        orderUserApplyAllocation.setAllocationTime(userApply.getAllocationTime());
//        orderUserApplyAllocation.setSubmitTime(userApply.getSubmitTime());
//        orderUserApplyAllocation.setAllocationType(OrderAllocationTypeEnum.ALLOCATION_RULE.getValue());
//        orderUserApplyAllocation.setApplyCity(userApply.getCity());
//        orderUserApplyAllocation.setLoanAmount(applyDetail.getLoanAmount());
//        orderUserApplyAllocation.setLoanPeriod(applyDetail.getLoanPeriod());
//        orderUserApplyAllocation.setCurrentAccountId(allocationMerchant.getAccountId());
//        orderUserApplyAllocation.setMerchantId(allocationMerchant.getMerchantId());
//        orderUserApplyAllocation.setProductId(allocationMerchant.getProductId());
//        orderUserApplyAllocation.setChannelPromotionPrice(userApply.getChannelPromotionPrice());
//        orderUserApplyAllocation.setChannelPromotionPriceVersion(userApply.getChannelPromotionPriceVersion());
//        ProductPriceInfo productPriceInfo = productExternalService.getProductPriceInfoByProductId(allocationMerchant.getProductId());
//        orderUserApplyAllocation.setProductPrice(productPriceInfo.getProductPrice());
//        orderUserApplyAllocation.setProductPriceVersion(productPriceInfo.getProductPriceVersion());
//        orderUserApplyAllocation.setApiLibraryNo(allocationMerchant.getApiLibraryOrderNo());
//        orderUserApplyAllocation.setApiUrl(allocationMerchant.getApiOrderUrl());
//        return orderUserApplyAllocation;
//    }
//
//    /**
//     * 订单分配成功
//     *
//     * @param orderUserApplyAllocation orderUserApplyAllocation
//     * @param userApply                userApply
//     * @param clientIp                 clientIp
//     */
//    public void allocationOrderSuccess(OrderUserApplyAllocation orderUserApplyAllocation, OrderUserApply userApply, Integer sex, String clientIp) {
//        if (Objects.nonNull(orderUserApplyAllocation.getProductId())) {
//            // 产品转化统计
//            ProductStatistics productStatistics = new ProductStatistics();
//            productStatistics.setProductId(orderUserApplyAllocation.getProductId());
//            productStatistics.setMerchantId(orderUserApplyAllocation.getMerchantId());
//            productStatistics.setProductPrice(orderUserApplyAllocation.getProductPrice());
//            productStatistics.setType(ProductStatisticsTypeEnum.ALLOCATION_ORDER);
//            productStatistics.setUserName(orderUserApplyAllocation.getUserName());
//            productStatistics.setUserPhone(orderUserApplyAllocation.getUserPhone());
//            productStatistics.setSex(sex);
//            orderStatisticsHandle.statisticsProductTransform(productStatistics);
//            //调用渠道推广转化统计
//            if (orderUserApplyAllocation.getProductId().equals(allocationDefaultProductId)) {
//                orderStatisticsHandle.statisticsChannelPromotionTransform(userApply.getChannelId(), userApply.getChannelPromotionCode(), orderUserApplyAllocation.getChannelPromotionPrice(), orderUserApplyAllocation.getProductPrice(), PromotionStatisticsTypeEnum.FROM_INFERIOR);
//            } else {
//                orderStatisticsHandle.statisticsChannelPromotionTransform(userApply.getChannelId(), userApply.getChannelPromotionCode(), orderUserApplyAllocation.getChannelPromotionPrice(), orderUserApplyAllocation.getProductPrice(), PromotionStatisticsTypeEnum.FROM);
//            }
//            //用户分配统计
//            orderStatisticsHandle.statisticsUserAllocation(userApply.getUserCode(), orderUserApplyAllocation.getAllocationTime());
//            // 分配埋点
//            SaveUserBuryingPointData saveUserBuryingPointData = new SaveUserBuryingPointData();
//            saveUserBuryingPointData.setVisitorId(userApply.getVisitorId());
//            saveUserBuryingPointData.setIp(clientIp);
//            saveUserBuryingPointData.setUserCode(userApply.getUserCode());
//            saveUserBuryingPointData.setBuryingPointTypeEnum(UserBuryingPointTypeEnum.ORDER_APPLY_ALLOCATION);
//            saveUserBuryingPointData.setData(JacksonUtils.X.format(orderUserApplyAllocation));
//            pointExternalService.saveUserBuryingPointData(saveUserBuryingPointData);
//        }
//
//    }
//
//
//    /**
//     * 推送api对接商户订单
//     *
//     * @param clientIp    clientIp
//     * @param userApply   userApply
//     * @param applyDetail applyDetail
//     * @param detailDTO   detailDTO
//     * @return ProductAllocationDetail
//     */
//    private ProductAllocationDetail pushMerchantOrderByApi(String clientIp, OrderUserApply userApply, OrderUserApplyDetail applyDetail, ProductAllocationDetail detailDTO) {
//        BaseActionListener merchantActionListener = merchantActionFactory.getMerchantActionListener(detailDTO.getMerchantId());
//        ProductQualityConfig quality = productQualityConfigService.selectQualityByProductId(detailDTO.getProductId());
//        if (Objects.isNull(merchantActionListener)) {
//            return detailDTO;
//        } else {
//            PushOrderDTO pushOrderDTO = new PushOrderDTO();
//            pushOrderDTO.setOrderNo(detailDTO.getApiLibraryOrderNo());
//            pushOrderDTO.setPhone(userApply.getUserPhone());
//            pushOrderDTO.setClientIp(clientIp);
//            pushOrderDTO.setAge(applyDetail.getAge());
//            pushOrderDTO.setSex(applyDetail.getSex());
//            pushOrderDTO.setId(userApply.getId());
//            pushOrderDTO.setProductId(detailDTO.getProductId());
//            pushOrderDTO.setApplyOrderNo(applyDetail.getApplyOrderNo());
//            pushOrderDTO.setMerchantId(detailDTO.getMerchantId());
//            pushOrderDTO.setUserCode(userApply.getUserCode());
//            if (quality != null) {
//                if (quality.getAgeSwitch() == 1) {
//                    pushOrderDTO.setAge(quality.getAge());
//                }
//                if (quality.getSexSwitch() == 1) {
//                    pushOrderDTO.setSex(quality.getSex());
//                }
//            }
//            OrderConverter.converterBaseOrderDTO(pushOrderDTO, userApply, applyDetail, quality);
//            long starTime = System.currentTimeMillis();
//            String apiResult = merchantActionListener.requestAction(MerchantActionCodeEnum.PUSH_ORDER, pushOrderDTO);
//            long endTime = System.currentTimeMillis();
//            log.info("产品{}进件耗时={}", detailDTO.getProductId(), endTime - starTime);
//            if (StringUtils.isBlank(apiResult)) {
//                // 进件记录
//                LibraryOrPushOrderStatistics statistics = new LibraryOrPushOrderStatistics();
//                statistics.setApplyNo(applyDetail.getApplyOrderNo());
//                statistics.setProductId(detailDTO.getProductId().intValue());
//                statistics.setMerchantId(detailDTO.getMerchantId().intValue());
//                statistics.setCrateTime(new Date());
//                statistics.setStatus(2);
//                statistics.setType(2);
//                try {
//                    libraryOrderStatisticsService.saveLibraryOrderStatistics(statistics);
//                } catch (Exception e) {
//                    log.error("进件记录异常,applyOrderNo={},productId={}, e", applyDetail.getApplyOrderNo(), detailDTO.getProductId(), e);
//                }
//                return null;
//            } else {
//                // 进件记录
//                LibraryOrPushOrderStatistics statistics = new LibraryOrPushOrderStatistics();
//                statistics.setApplyNo(applyDetail.getApplyOrderNo());
//                statistics.setProductId(detailDTO.getProductId().intValue());
//                statistics.setMerchantId(detailDTO.getMerchantId().intValue());
//                statistics.setCrateTime(new Date());
//                statistics.setStatus(1);
//                statistics.setType(2);
//                try {
//                    libraryOrderStatisticsService.saveLibraryOrderStatistics(statistics);
//                } catch (Exception e) {
//                    log.error("进件记录异常,applyOrderNo={},productId={}, e", applyDetail.getApplyOrderNo(), detailDTO.getProductId(), e);
//                }
//                if (!"公共下游".equals(apiResult)) {
//                    detailDTO.setApiOrderUrl(apiResult);
//                    if (apiResult.contains("YXY_KEY")) {
//                        String[] split = apiResult.split("YXY_KEY");
//                        detailDTO.setProtocol(split[1]);
//                        detailDTO.setApiOrderUrl(split[0] + "YXY_KEY");
//                    }
//                }
//                return detailDTO;
//            }
//        }
//    }
//
//
//}
